# 子域名爆破脚本——多线程版
import threading
import socket
import time

sub_domain_filename = 'sub_domain.txt'

# 线程锁和临界资源：
threadLock = threading.Lock()
resultList = []

# 多线程类，用于并发挖掘
class DomainMinner(threading.Thread):
    def __init__(self,domain):
        threading.Thread.__init__(self)
        self.domain = domain
    def run(self):
        iplist = domainToip(self.domain)
        subDomain = {}
        if len(iplist) > 0:
            subDomain['domain'] = self.domain
            subDomain['iplist'] = iplist
            # 判断是否可能存在CDN
            subDomain['isCDN'] = False
            if len(iplist) > 1:
                subDomain['isCDN'] = True
            # 临界区：
            threadLock.acquire()
            resultList.append(subDomain)
            threadLock.release()

# DNS解析
def domainToip(domain):
    iplist = []
    try:
        results = socket.getaddrinfo(domain , None)
        for item in results:
            iplist.append(item[4][0])
    except Exception as e:
        print("domain:" + domain + " info:")
        print(e)
    return iplist

# 读取子域名字典
def readSubDomainList():
    subDomainList = []
    try:
        file = open(sub_domain_filename, 'r')
        for line in file:
            subDomainList.append(line[:-1])
            # 这里切片的作用是去掉换行
        file.close()
    except Exception as e:
        print(e)
    return subDomainList

# 拼接子域名
def splitSubDomain(domain,subDomainList):
    subDomains = []
    for item in subDomainList:
        subDomains.append(item + '.' + domain)
    return subDomains

# 子域名挖掘主函数
def subDominMining(domain):
    threads = []
    subDomainList = readSubDomainList()
    subDomains = splitSubDomain(domain,subDomainList)
    try:
        for item in subDomains:
            thread = DomainMinner(item)
            threads.append(thread)
            thread.start()
        for thread in threads:
            thread.join()
    except Exception as e:
        print(e)
    accessible = resultList
    return accessible

if __name__ == "__main__":
    star_time = time.time()
    domain = "bing.com"
    results = subDominMining(domain)
    end_time =time.time()
    for item in results:
        print(item)
    print("用时：" + str(end_time - star_time))